package com.parking.carsystem.parkingchargesystem.activity;

import android.content.Intent;
import android.os.Message;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.EnvUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.parking.carsystem.parkingchargesystem.R;
import com.parking.carsystem.parkingchargesystem.common.Constant;
import com.parking.carsystem.parkingchargesystem.module.AbsenceData;
import com.parking.carsystem.parkingchargesystem.module.CouponNotUseModel;
import com.parking.carsystem.parkingchargesystem.module.SelfServicePaymentModule;
import com.parking.carsystem.parkingchargesystem.view.BottomDialog;

import java.util.ArrayList;
import java.util.Objects;

import butterknife.BindView;

public class SelfServicePaymentActivity extends BaseActivity implements View.OnClickListener, BottomDialog.ChooseTextLisenter {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.not_data)
    ImageView not_data;
    @BindView(R.id.parking_message)
    RelativeLayout parkingMessage;
    @BindView(R.id.park_icon)
    ImageView parkIcon;
    @BindView(R.id.parking_name)
    TextView parkingName;
    @BindView(R.id.line_one)
    View lineOne;
    @BindView(R.id.order_number)
    TextView orderNumber;
    @BindView(R.id.order_number_data)
    RelativeLayout orderNumberData;
    @BindView(R.id.charging_start_time)
    TextView chargingStartTime;
    @BindView(R.id.charging_start_data)
    RelativeLayout chargingStartData;
    @BindView(R.id.charging_end_time)
    TextView chargingEndTime;
    @BindView(R.id.order_number_data_end)
    RelativeLayout orderNumberDataEnd;
    @BindView(R.id.charging_duration)
    TextView chargingDuration;
    @BindView(R.id.charging_duration_data)
    RelativeLayout chargingDurationData;
    @BindView(R.id.charging_money)
    TextView chargingMoney;
    @BindView(R.id.charging_money_data)
    RelativeLayout chargingMoneyData;
    @BindView(R.id.line_two)
    View lineTwo;
    @BindView(R.id.coupon)
    TextView coupon;
    @BindView(R.id.coupon_data)
    RelativeLayout couponData;
    @BindView(R.id.line_three)
    TextView lineThree;
    @BindView(R.id.subtotal)
    TextView subtotal;
    @BindView(R.id.subtotal_data)
    RelativeLayout subtotalData;
    @BindView(R.id.bill_message)
    RelativeLayout billMessage;
    @BindView(R.id.pay_parking)
    TextView payParking;
    @BindView(R.id.palte_number)
    TextView palte_number;
    @BindView(R.id.blue_parking_style)
    TextView blueParkingStyle;
    @BindView(R.id.switch_plate)
    ImageView switchPlate;
    private ArrayList<AbsenceData> absenceData;
    private BottomDialog bottomDialog;
    private boolean flag;
    private ArrayList<AbsenceData> absenceDataPay;
    private BottomDialog bottomDialogPay;
    private SelfServicePaymentModule.DataBean data;
    private String plateNumber;
    private String code = "";

    @Override
    protected int getContentViewId() {
        return R.layout.activity_payment;
    }

    @Override
    public void initView() {
        back.setOnClickListener(this);
        switchPlate.setOnClickListener(this);
        coupon.setOnClickListener(this);
        payParking.setOnClickListener(this);
    }

    @Override
    public void initData() {
        //支付宝的开启沙箱环境支付
//        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        text.setText("自助缴费");
        plateNumber = getIntent().getStringExtra(Constant.PLATENUMBER);
        code = getIntent().getStringExtra(Constant.PAYCODE);
        palte_number.setText(plateNumber);
        back.setVisibility(View.VISIBLE);
        absenceDataPay = new ArrayList<>();
        absenceDataPay.add(new AbsenceData("支付宝", true));
        absenceDataPay.add(new AbsenceData("微信", false));
        absenceDataPay.add(new AbsenceData("账户余额", false));
        bottomDialogPay = new BottomDialog(absenceDataPay.size(), this, 1);
        bottomDialogPay.setChooseTextLisenter(this);
        bottomDialogPay.setTitle("支付方式");
        bottomDialogPay.setBottomTitle("确认支付");
        bottomDialogPay.setBottomData(absenceDataPay);
        serachPlatePayMessage(plateNumber, code);
    }

    private void serachPlatePayMessage(String plateNumber, String couponCode) {
        showLoading();
        OkGo.<String>get(Constant.url + Constant.SELECTPREPAYORDER)
                .params("plateNumber", plateNumber)
                .params("couponCode", couponCode)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        stopLoading();
                        Gson gson = new Gson();
                        SelfServicePaymentModule selfServicePaymentModule = gson.fromJson(response.body(), SelfServicePaymentModule.class);
                        if (selfServicePaymentModule.code == 200) {
                            data = selfServicePaymentModule.data;
                            if (data != null) {
                                not_data.setVisibility(View.GONE);
                                parkingName.setText(data.parkinglotName);
                                orderNumber.setText(data.orderNo);
                                chargingStartTime.setText(data.calcStartTime);
                                chargingEndTime.setText(data.calcEndTime);
                                chargingDuration.setText(data.calcPeriod);
                                chargingMoney.setText(String.valueOf("¥" + data.totalFee));
                                subtotal.setText(String.valueOf("¥" + data.fee));
                                getCouponMessage();
                            }
                        } else {
                            not_data.setVisibility(View.VISIBLE);
                            showToast(selfServicePaymentModule.msg);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        not_data.setVisibility(View.VISIBLE);
                        stopLoading();
                    }
                });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.switch_plate:
                //切换车牌
//                showToast("切换车牌");
                Intent intent = new Intent(this, ChooseLisencePlateActivity.class);
                intent.putExtra(Constant.SELFSERVICEPAYMENT, Constant.SELFSERVICEPAYMENT);
                startActivityForResult(intent, 0);
                break;
            case R.id.coupon:
                if (absenceData != null && absenceData.size() > 0) {
                    bottomDialog.show();
                } else {
                    showToast("暂无可用优惠卷");
                }
                break;
            case R.id.pay_parking:
                if (data != null && !TextUtils.isEmpty(data.outTradeNo)) {
                    bottomDialogPay.show();
                } else {
                    showToast("暂无需要支付的金额");
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Constant.PLATENUMBERCODE == resultCode) {
            //点击车牌过来的
            String plateNumber = data.getStringExtra(Constant.PLATENUMBER);
            int plateColor = data.getIntExtra(Constant.PLATECOLOR, 1);
            if (plateColor == 0) {
                //蓝牌车
                blueParkingStyle.setText("蓝牌车");
                blueParkingStyle.setBackgroundResource(R.drawable.parking_blue_self_backgroud);
                blueParkingStyle.setTextColor(getResources().getColor(R.color.white));
            } else if (plateColor == 1) {
                //黄牌车
                blueParkingStyle.setText("黄牌车");
                blueParkingStyle.setBackgroundResource(R.drawable.parking_yellow_type_style);
                blueParkingStyle.setTextColor(getResources().getColor(R.color.white));
            } else if (plateColor == 2) {
                //特种车
                blueParkingStyle.setText("特种车");
                blueParkingStyle.setBackgroundResource(R.drawable.parking_other_type_style);
                blueParkingStyle.setTextColor(getResources().getColor(R.color.diff_text_color));
            }
            palte_number.setText(plateNumber);
            serachPlatePayMessage(plateNumber, code);
        }
    }

    @Override
    public void chooseText(AbsenceData text) {
        //点击返回的内容
        if (text.text.equals("支付宝") || text.text.equals("微信") || text.text.equals("账户余额")) {
            if (data.fee > 0) {
                if (text.text.equals("微信")) {
                    payWeiXin(data.outTradeNo);
                } else if (text.text.equals("支付宝")) {
                    payAli(data.outTradeNo);
                } else if (text.text.equals("账户余额")) {
                    accountPay(data.outTradeNo);
                }
            } else {
                //优惠后的金额为0,然后就不需要调用第三方支付了
                payZero();
            }
        } else {
            coupon.setText(text.text);
            //选择优惠券重新请求
            serachPlatePayMessage(plateNumber, text.code);
        }
    }

    private void payZero() {
        showLoading();
        OkGo.<String>get(Constant.url + Constant.COUPONPAY)
                .params("outTradeNo", data.outTradeNo)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        stopLoading();
                        boolean parseJson = parseJson(response.body());
                        if (parseJson) {
                            showToast("优惠卷支付成功!");
                            finish();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        stopLoading();
                        showToast(response.message());
                    }
                });
    }

    /**
     * 获取优惠券的信息
     */
    private void getCouponMessage() {
        showLoading();
        OkGo.<String>get(Constant.url + Constant.COUPONLISTCANUSE)
                .params("parkinglotId", data.parkinglotId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        stopLoading();
                        Gson gson = new Gson();
                        CouponNotUseModel couponNotUseModel = gson.fromJson(response.body(), CouponNotUseModel.class);
                        if (couponNotUseModel.code == 200) {
                            if (absenceData == null) {
                                absenceData = new ArrayList<>();
                            }
                            absenceData.clear();
                            for (int i = 0; i < couponNotUseModel.rows.size(); i++) {
                                CouponNotUseModel.RowsBean rowsBean = couponNotUseModel.rows.get(i);
                                if (i == 0) {
                                    absenceData.add(new AbsenceData(rowsBean.code, rowsBean.couponName, true));
                                }
                                absenceData.add(new AbsenceData(rowsBean.code, rowsBean.couponName, false));
                            }
                            bottomDialog = new BottomDialog(absenceData.size(), SelfServicePaymentActivity.this, 1);
                            bottomDialog.setTitle("优惠券");
                            bottomDialog.setBottomTitle("完成");
                            bottomDialog.setChooseTextLisenter(SelfServicePaymentActivity.this);
                            bottomDialog.setBottomData(absenceData);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        stopLoading();
                    }
                });
    }

    public void handleMessageMeathed(Message msg) {
        boolean payResponse = payResponse(msg);
        if (payResponse) {
            serachPlatePayMessage(plateNumber, code);
        }
    }
}
